package com.wjbgn.bsolver.server.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.wjbgn.bsolver.server.convert.BugRecordDoConvert;
import com.wjbgn.bsolver.server.dto.AchievementDTO;
import com.wjbgn.bsolver.server.dto.BugRecordDTO;
import com.wjbgn.bsolver.server.entity.BugRecordDO;
import com.wjbgn.bsolver.server.entity.CategoryDO;
import com.wjbgn.bsolver.server.enums.ConditionEnum;
import com.wjbgn.bsolver.server.service.IBugAnsweredRecordService;
import com.wjbgn.bsolver.server.service.IBugRecordService;
import com.wjbgn.bsolver.server.service.ICategoryService;
import com.wjbgn.bsolver.server.util.UserInfoCacheUtil;
import com.wjbgn.stater.dto.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * Create Date: 2022-04-16T16:09:33.187
 *
 * @author wjbgn
 * @version 1.0
 */
@Api(tags = "")
@RestController
@RequestMapping("/bugrecord")
@AllArgsConstructor
public class BugRecordController {

    /**
     * BugRecordService
     */
    private IBugRecordService bugRecordService;

    private ICategoryService categoryService;

    private IBugAnsweredRecordService bugAnsweredRecordService;

    private UserInfoCacheUtil userInfoCacheUtil;

    /**
     * 首页分页列表
     *
     * @param bugRecordDTO
     * @return
     */
    @ApiOperation(value = "分页列表")
    @GetMapping("/pageList")
    public Result pageList(BugRecordDTO bugRecordDTO) {
        Page<BugRecordDO> pageList = bugRecordService.findByPageable(bugRecordDTO);

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BugRecordDTO> pageInfo
                = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                bugRecordDTO.getPage(), bugRecordDTO.getLimit());
        pageInfo.setTotal(pageList.getTotalElements());

        if (CollectionUtil.isEmpty(pageList.getContent())) {
            return Result.success(pageInfo);
        }
        // 处理查询结果
        List<BugRecordDO> content = pageList.getContent();
        List<BugRecordDTO> bugRecordDTOS = BugRecordDoConvert.listConvert(content);

        Set<Integer> categoryIds = new HashSet<>();
        bugRecordDTOS.forEach(bug -> {
            for (String s : bug.getCategory().split(",")) {
                categoryIds.add(Integer.parseInt(s));
            }
        });
        List<CategoryDO> categoryDOS = categoryService.listByIds(categoryIds);
        Map<Long, String> collect = categoryDOS.stream().collect(Collectors.toMap(k -> k.getId(), v -> v.getName()));
        bugRecordDTOS.forEach(c -> {
            c.setCreateTimeStr(DateUtil.format(c.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            List<String> list = new ArrayList<>();
            for (String s : c.getCategory().split(",")) {
                list.add(collect.get(Long.parseLong(s)));
            }
            c.setCategoriesName(list);
            c.setNickname(userInfoCacheUtil.getUserNicknameByUsername(c.getUsername()));
        });

        pageInfo.setRecords(bugRecordDTOS);
        pageInfo.setTotal(pageList.getTotalElements());
        return Result.success(pageInfo);
    }

    /**
     * 个人中心分页列表
     *
     * @param bugRecordDTO
     * @return
     */
    @ApiOperation(value = "分页列表")
    @GetMapping("/userCenterPageList")
    public Result userCenterPageList(BugRecordDTO bugRecordDTO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BugRecordDTO> pageInfo
                = bugRecordService.findUserCenterByPageable(bugRecordDTO);
        // 处理查询结果
        List<BugRecordDTO> bugRecordDTOS = pageInfo.getRecords();
        if (CollectionUtil.isNotEmpty(bugRecordDTOS)) {
            Set<Integer> categoryIds = new HashSet<>();
            bugRecordDTOS.forEach(bug -> {
                for (String s : bug.getCategory().split(",")) {
                    categoryIds.add(Integer.parseInt(s));
                }
            });
            List<CategoryDO> categoryDOS = categoryService.listByIds(categoryIds);
            Map<Long, String> collect = categoryDOS.stream().collect(Collectors.toMap(k -> k.getId(), v -> v.getName()));
            bugRecordDTOS.forEach(c -> {
                c.setCreateTimeStr(DateUtil.format(c.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                List<String> list = new ArrayList<>();
                for (String s : c.getCategory().split(",")) {
                    list.add(collect.get(Long.parseLong(s)));
                }
                c.setCategoriesName(list);
                c.setNickname(userInfoCacheUtil.getUserNicknameByUsername(c.getUsername()));
            });
            pageInfo.setRecords(bugRecordDTOS);
        }
        return Result.success(pageInfo);
    }

    @ApiOperation(value = "保存")
    @PostMapping("/save")
    public Result save(@RequestBody BugRecordDTO bugRecordDTO) {
        BugRecordDO save = bugRecordService.save(BugRecordDoConvert.dtoToDo(bugRecordDTO));
        return Result.success(save);
    }

    @ApiOperation(value = "获取用户成就统计")
    @GetMapping("/getUserAchievement")
    public Result getUserAchievement(@RequestParam("username") String username) {
        BugRecordDTO bugRecordDTO = new BugRecordDTO();
        bugRecordDTO.setUsername(username);
        bugRecordDTO.setPage(1);
        bugRecordDTO.setLimit(1);
        // 获取我提出数量
        bugRecordDTO.setSearchCondition(ConditionEnum.ASKED.getCode());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BugRecordDTO> asked
                = bugRecordService.findUserCenterByPageable(bugRecordDTO);
        // 获取我回答数量
        bugRecordDTO.setSearchCondition(ConditionEnum.ANSWERED.getCode());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BugRecordDTO> answered
                = bugRecordService.findUserCenterByPageable(bugRecordDTO);
        // 获取被采纳数/获取被嫌弃数
        AchievementDTO achievementDTO = bugAnsweredRecordService.getAcceptAndRejectNum(username);
        achievementDTO.setAnsweredNum(answered.getTotal());
        achievementDTO.setAskedNum(asked.getTotal());
        return Result.success(achievementDTO);
    }
}